package org.example.cloud.utils;

import jakarta.mail.Message;
import jakarta.mail.MessagingException;
import jakarta.mail.PasswordAuthentication;
import jakarta.mail.Session;
import jakarta.mail.Transport;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import org.example.cloud.bean.EmailProperties;

import java.util.Properties;
import jakarta.mail.Authenticator;

public class MailUtil {
    /**
     * @param emailProperties 发件人信息（发件人邮箱，发件人授权码）及邮件服务器信息（邮件服务器域名，身份验证开关）
     * @param to              收件人邮箱
     * @param title           邮件标题
     * @param content         邮件内容
     * @return
     */
    public static boolean send(EmailProperties emailProperties, String to, String title, String content) {
        // 设置邮件服务器的主机名和端口
        String host = emailProperties.getHost();
        int port = 465; // QQ邮箱的SMTP端口为465

        // 设置发件人邮箱和授权码
        String user = emailProperties.getUser();
        String password = emailProperties.getCode();

        // 创建Properties对象，用于设置邮件服务器的主机名和端口
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", emailProperties.isAuth());
        properties.put("mail.smtp.ssl.enable", "true"); // 启用 SSL
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        // 创建Session对象，用于发送邮件
        Session session = Session.getInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        });

        try {
            // 创建MimeMessage对象，用于构建邮件内容
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(user)); // 设置发件人
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to)); // 设置收件人
            message.setSubject(title); // 设置邮件标题
            message.setText(content); // 设置邮件内容

            // 打印调试信息
            System.out.println("Sending email to: " + to);
            System.out.println("Email title: " + title);
            System.out.println("Email content: " + content);

            // 发送邮件
            Transport.send(message);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }

}
